<?php
/**
 * 其他辅助功能
 * 相对路径: adm/more.php
 * 作者: 15058593138@qq.com
 */

// 清空历史记录
if (isset($_GET['act']) && $_GET['act'] === 'clean') {
    $days = isset($_POST['days']) ? intval($_POST['days']) : 0;
    
    if ($days <= 0) {
        jsonMsg(0, '请输入有效的天数');
    }
    
    $db = new DB();
    $deleted = 0;
    
    // 获取N天前的日期列表
    for ($i = $days; $i >= 1; $i--) {
        $date = date('Ymd', strtotime("-{$i} days"));
        $table = TB_PREFIX . 'recs_' . $date;
        
        if ($db->tableExists($table)) {
            if ($db->query("DROP TABLE `{$table}`")) {
                $deleted++;
            }
        }
    }
    
    $db->close();
    jsonMsg(1, "成功删除{$deleted}个历史表");
}

// 数据库备份
if (isset($_GET['act']) && $_GET['act'] === 'backup') {
    $db = new DB();
    
    // 获取所有表
    $tables = [];
    $result = $db->query("SHOW TABLES LIKE '" . TB_PREFIX . "%'");
    while ($row = $result->fetch_row()) {
        $tables[] = $row[0];
    }
    
    $sql = "-- 数据库备份\n";
    $sql .= "-- 生成时间: " . date('Y-m-d H:i:s') . "\n\n";
    
    foreach ($tables as $table) {
        // 获取建表语句
        $createTable = $db->getRow("SHOW CREATE TABLE `{$table}`");
        $sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
        $sql .= $createTable['Create Table'] . ";\n\n";
        
        // 获取数据
        $rows = $db->getAll("SELECT * FROM `{$table}`");
        if (count($rows) > 0) {
            foreach ($rows as $row) {
                $values = [];
                foreach ($row as $val) {
                    $values[] = "'" . $db->escape($val) . "'";
                }
                $sql .= "INSERT INTO `{$table}` VALUES (" . implode(',', $values) . ");\n";
            }
            $sql .= "\n";
        }
    }
    
    $db->close();
    
    $filename = 'backup_' . date('YmdHis') . '.sql';
    jsonMsg(1, '备份成功', ['sql' => $sql, 'filename' => $filename]);
}

// 统计数据
if (isset($_GET['act']) && $_GET['act'] === 'stats') {
    $db = new DB();
    $rooms = readJson('./inc/weici.json.php');
    $stats = [];
    
    // 统计最近7天的数据
    $dates = getDateRange(7);
    
    foreach ($rooms as $room) {
        $roomCode = $room['room'];
        $roomName = $room['name'];
        $totalSeats = countSeats($room['layout']);
        
        $roomStats = [
            'room' => $roomCode,
            'name' => $roomName,
            'total_seats' => $totalSeats,
            'dates' => []
        ];
        
        foreach ($dates as $date) {
            $recTable = TB_PREFIX . 'recs_' . $date;
            if (!$db->tableExists($recTable)) continue;
            
            $dateStats = [
                'date' => $date,
                'jiecis' => []
            ];
            
            // 获取所有节次
            $jiecis = readJson('./inc/jieci.json.php');
            foreach ($jiecis as $jieci) {
                $jieciCode = $jieci['code'];
                
                $sql = "SELECT COUNT(*) FROM `{$recTable}` WHERE `room` = '{$roomCode}' AND `days` = '{$jieciCode}' AND `stats` = 1";
                $booked = $db->getCount($sql);
                
                $dateStats['jiecis'][] = [
                    'jieci' => $jieciCode,
                    'name' => $jieci['name'],
                    'booked' => $booked,
                    'available' => $totalSeats - $booked
                ];
            }
            
            $roomStats['dates'][] = $dateStats;
        }
        
        $stats[] = $roomStats;
    }
    
    $db->close();
    jsonMsg(1, '统计成功', $stats);
}

require_once './inc/head.php';
?>

<div class="container">
    <div style="display:grid; grid-template-columns:1fr 1fr; gap:15px; margin-bottom:15px;">
        <!-- 清空历史记录 -->
        <div class="table-wrapper">
            <div style="padding:20px;">
                <h3>清空历史记录</h3>
                
                <form id="cleanForm" style="margin-top:20px;">
                    <div class="form-group">
                        <label>清空天数</label>
                        <input type="number" name="days" class="form-control" 
                               placeholder="输入天数，如：30（清空30天前的记录）" min="1" required>
                    </div>
                    
                    <div class="form-group">
                        <button type="submit" class="btn btn-danger">清空记录</button>
                    </div>
                    
                    <div style="color:#dc3545; font-size:12px; margin-top:10px;">
                        <p>⚠️ 注意：此操作将永久删除历史数据表，请谨慎操作！</p>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 数据库备份 -->
        <div class="table-wrapper">
            <div style="padding:20px;">
                <h3>数据库备份</h3>
                
                <div style="margin-top:20px;">
                    <p style="color:#666; margin-bottom:15px;">
                        点击下方按钮将导出所有数据表的SQL备份文件
                    </p>
                    
                    <button class="btn btn-success" onclick="backupDB()">导出备份</button>
                    
                    <div style="color:#666; font-size:12px; margin-top:15px;">
                        <p>备份包含：</p>
                        <ul style="margin-left:20px;">
                            <li>用户表数据</li>
                            <li>所有预定记录表</li>
                            <li>表结构和数据</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 数据统计 -->
    <div class="table-wrapper">
        <div style="padding:20px;">
            <h3>数据统计（最近7天）</h3>
            <button class="btn btn-primary" style="float:right; margin-top:-35px;" onclick="loadStats()">刷新统计</button>
            
            <div id="statsContainer" style="margin-top:20px;">
                <p style="text-align:center; color:#666;">点击刷新统计按钮查看数据</p>
            </div>
        </div>
    </div>
</div>

<script>
    // 清空历史记录
    document.getElementById('cleanForm').onsubmit = function(e) {
        e.preventDefault();
        
        const formData = getFormData('cleanForm');
        const days = formData.days;
        
        showModal('确认清空', 
            `<p style="color:#dc3545;">此操作将删除 ${days} 天前的所有预定记录表！</p>
             <p>确定要继续吗？</p>`, [
            {text: '取消', class: 'btn-secondary', onclick: 'closeModal()'},
            {text: '确定清空', class: 'btn-danger', onclick: `doClean(${days})`}
        ]);
    };
    
    function doClean(days) {
        closeModal();
        showLoading();
        
        ajax('admin.php?do=more&act=clean', {days: days}, function(res) {
            hideLoading();
            if (res.code === 1) {
                toast(res.msg, 'success');
                document.getElementById('cleanForm').reset();
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 数据库备份
    function backupDB() {
        showLoading();
        
        ajax('admin.php?do=more&act=backup', {}, function(res) {
            hideLoading();
            if (res.code === 1) {
                // 下载SQL文件
                const blob = new Blob([res.data.sql], {type: 'text/plain;charset=utf-8;'});
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = res.data.filename;
                link.click();
                toast('备份成功', 'success');
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 加载统计数据
    function loadStats() {
        showLoading();
        
        ajax('admin.php?do=more&act=stats', {}, function(res) {
            hideLoading();
            if (res.code === 1) {
                renderStats(res.data);
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 渲染统计数据
    function renderStats(data) {
        const container = document.getElementById('statsContainer');
        
        if (data.length === 0) {
            container.innerHTML = '<p style="text-align:center; color:#666;">暂无数据</p>';
            return;
        }
        
        let html = '';
        
        data.forEach(room => {
            html += `<div style="margin-bottom:20px; border:1px solid #eee; border-radius:5px; padding:15px;">
                <h4 style="cursor:pointer;" onclick="toggleRoom('room_${room.room}')">
                    ▼ ${room.name} (${room.room}) - 总座位: ${room.total_seats}
                </h4>
                <div id="room_${room.room}" style="display:none; margin-top:10px;">`;
            
            room.dates.forEach(date => {
                const dateFormat = date.date.substr(0,4) + '-' + date.date.substr(4,2) + '-' + date.date.substr(6,2);
                let totalBooked = 0;
                date.jiecis.forEach(j => totalBooked += j.booked);
                
                html += `<div style="margin-left:20px; margin-bottom:10px;">
                    <h5 style="cursor:pointer;" onclick="toggleDate('date_${room.room}_${date.date}')">
                        ▼ ${dateFormat} - 已约: ${totalBooked}
                    </h5>
                    <div id="date_${room.room}_${date.date}" style="display:none; margin-top:5px;">
                        <table class="table" style="font-size:12px;">
                            <thead>
                                <tr>
                                    <th>节次</th>
                                    <th>已约</th>
                                    <th>余位</th>
                                    <th>使用率</th>
                                </tr>
                            </thead>
                            <tbody>`;
                
                date.jiecis.forEach(jieci => {
                    const rate = ((jieci.booked / room.total_seats) * 100).toFixed(1);
                    html += `<tr>
                        <td>${jieci.name}</td>
                        <td>${jieci.booked}</td>
                        <td>${jieci.available}</td>
                        <td>${rate}%</td>
                    </tr>`;
                });
                
                html += `</tbody></table></div></div>`;
            });
            
            html += '</div></div>';
        });
        
        container.innerHTML = html;
    }
    
    // 切换显示
    function toggleRoom(id) {
        const el = document.getElementById(id);
        el.style.display = el.style.display === 'none' ? 'block' : 'none';
    }
    
    function toggleDate(id) {
        const el = document.getElementById(id);
        el.style.display = el.style.display === 'none' ? 'block' : 'none';
    }
</script>

<?php require_once './inc/foot.php'; ?>